package com.buyi.easyhome.util

import android.content.res.AssetFileDescriptor
import android.media.MediaPlayer
import java.io.IOException


class AudioPlayer {
    private val mediaPlayer: MediaPlayer = MediaPlayer()
    private val audioFiles: MutableList<AssetFileDescriptor> = ArrayList()
    private var currentFileIndex: Int = 0

    init {
        mediaPlayer.setOnCompletionListener { // 播放完成事件监听
            playNextAudio()
        }
    }

    fun addAudioFile(filePath: AssetFileDescriptor) {
        audioFiles.add(filePath)
    }

    fun play() {
        if (audioFiles.isNotEmpty()) {
            try {
                mediaPlayer.reset()
                mediaPlayer.setDataSource(audioFiles[currentFileIndex])
                mediaPlayer.prepare()
                mediaPlayer.start()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    fun pause() {
        mediaPlayer.pause()
    }

    fun stop() {
        mediaPlayer.stop()
    }

    private fun playNextAudio() {
        if (currentFileIndex < audioFiles.size - 1) {
            currentFileIndex++
            play()
        }
    }
}
